﻿using CommonClass;
using I_SheepManagement.Domains;
using I_SheepManagement.Infrastructure.Interface;
using I_SheepManagement.Read.API.Application.Command;
using MediatR;

namespace I_SheepManagement.Read.API.Application.CommandHandler
{
    public class DeathManageReadCommandHandler : IRequestHandler<DeathManageReadCommand, PageResult<DeathManagement>>
    {
        private readonly IDeathManagementRepository _sheepManagementRepository;

        public DeathManageReadCommandHandler(IDeathManagementRepository sheepManagementRepository)
        {
            _sheepManagementRepository = sheepManagementRepository;
        }

        public async Task<PageResult<DeathManagement>> Handle(DeathManageReadCommand request, CancellationToken cancellationToken)
        {
            var sheepManage = _sheepManagementRepository.GetByFuncListAsync(x => !x.IsDelete).Result.AsQueryable();

            if (!string.IsNullOrEmpty(request.EarNumber))
            {
                sheepManage = sheepManage.Where(a => a.EarNumber.Contains(request.EarNumber));
            }
            if (!string.IsNullOrEmpty(request.StartSheepDeath))
            {
                var startDate = DateTime.Parse(request.StartSheepDeath);
                sheepManage = sheepManage.Where(a => a.Deathdate >= startDate);
            }
            if (!string.IsNullOrEmpty(request.EndSheepDeath))
            {
                var endDate = DateTime.Parse(request.EndSheepDeath);
                sheepManage = sheepManage.Where(a => a.Deathdate <= endDate);
            }
            if (!string.IsNullOrEmpty(request.DeathCause))
                {
                sheepManage = sheepManage.Where(a => a.DeathCause.Equals(request.DeathCause));
            }

            var pageResult = new PageResult<DeathManagement>();

            if (sheepManage != null)
            {
                pageResult.TotalCount = sheepManage.Count();
                pageResult.PageCount = (int)Math.Ceiling(pageResult.TotalCount * 1.0 / request.Size);
                pageResult.Datas = sheepManage.OrderByDescending(a => a.Id).Skip(request.Size * (request.Index - 1)).Take(request.Size).ToList();
            }

            return pageResult;
        }
    }
}
